package com.zzyl.nursing.service.impl;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.domain.Contract;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SerialNumberGeneratorUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住信息Service业务层处理
 * 
 * @author alexis
 * @date 2025-02-24
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住信息
     * 
     * @param id 入住信息主键
     * @return 入住信息
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住信息列表
     * 
     * @param checkIn 入住信息
     * @return 入住信息
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住信息
     * 
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住信息
     * 
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住信息
     * 
     * @param ids 需要删除的入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息信息
     * 
     * @param id 入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto 入住请求DTO
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int applyCheckIn(CheckInApplyDto checkInApplyDto) {
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        List<ElderFamilyDto> elderFamilyDtos = checkInApplyDto.getElderFamilyDtoList();
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        // 1. 校验老人是否入住
        Elder elder = checkElderIsAlreadyCheckIn(checkInElderDto.getIdCardNo(), 1);
        // 2. 更新床位状态为已入住
        Bed bed = updateBedStatus(1, checkInConfigDto.getBedId());
        // 3. 新增或更新老人(判断老人是否存在)
        elder = insertOrUpdateElder(elder, bed, checkInElderDto);
        // 4. 新增入住合同信息
        insertCheckInContract(elder, checkInContractDto, checkInConfigDto);
        // 5. 新增入住信息
        Long checkInId = insertCheckInBaseInfo(elder, bed, checkInConfigDto, elderFamilyDtos);
        // 6. 新增入住配置信息
        insertCheckInConfig(checkInId, checkInConfigDto);
        return 1;
    }

    /**
     * 新增入住配置
     * @param checkInId 入住信息ID
     * @param checkInConfigDto 入住配置DTO
     */
    private void insertCheckInConfig(Long checkInId, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        checkInConfig.setCheckInId(checkInId);
        int rows = checkInConfigMapper.insert(checkInConfig);
        if(rows != 1){
            throw new BaseException("新增入住配置异常");
        }
    }

    /**
     * 新增入住信息
     * @param checkInConfigDto 入住配置DTO
     * @return 入住ID
     */
    private Long insertCheckInBaseInfo(Elder elder, Bed bed, CheckInConfigDto checkInConfigDto, List<ElderFamilyDto> elderFamilyDtos) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        if(CollUtil.isNotEmpty(elderFamilyDtos)){
            checkIn.setRemark(JSONUtil.toJsonStr(elderFamilyDtos));
        }
        checkInMapper.insert(checkIn);
        return checkIn.getId();
    }

    /**
     * 新增入住合同
     * @param elder 老人
     * @param checkInContractDto 入住合同DTO
     * @param checkInConfigDto 入住配置DTO
     */
    private void insertCheckInContract(Elder elder, CheckInContractDto checkInContractDto, CheckInConfigDto checkInConfigDto) {
        Contract contract = BeanUtil.toBean(checkInContractDto, Contract.class);
        contract.setElderId(elder.getId());
        contract.setContractNumber(SerialNumberGeneratorUtils.generate());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(0);
        int rows = contractMapper.insert(contract);
        if(rows != 1){
            throw new BaseException("保存入住合同失败");
        }
    }

    /**
     * 新增/修改老人信息
     * @param elder 原始老人数据
     * @param checkInElderDto 入住配置DTO
     * @return
     */
    private Elder insertOrUpdateElder(Elder elder, Bed bed, CheckInElderDto checkInElderDto) {
        // 判断入住老人信息是否已存在
        boolean flag = ObjectUtil.isNull(elder);
        elder = BeanUtil.toBean(checkInElderDto, Elder.class);
        elder.setStatus(1);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        if(flag){
            // 新增
            elderMapper.insert(elder);
        }else {
            // 修改
            elderMapper.updateById(elder);
        }
        // if(ObjectUtil.isNull(elder)){
        //     // 新增
        //     elder = BeanUtil.toBean(checkInElderDto, Elder.class);
        //     elder.setStatus(1);
        //     elder.setBedNumber(bed.getBedNumber());
        //     elder.setBedId(bed.getId());
        //     elderMapper.insert(elder);
        // }else {
        //     // 修改
        //     elder.setStatus(1);
        //     elder.setBedNumber(bed.getBedNumber());
        //     elder.setBedId(bed.getId());
        //     elderMapper.updateById(elder);
        // }
        return elder;
    }

    /**
     * 更新床位状态
     * @param status 床位状态
     * @param bedId 床位id
     * @return 最新bed对象
     */
    private Bed updateBedStatus(int status, Long bedId) {
        Bed bed = bedMapper.selectBedById(bedId);
        bed.setBedStatus(status);
        int row = bedMapper.updateById(bed);
        if(row != 1){
            throw new BaseException("床位状态更新失败");
        }
        return bed;
    }

    /**
     * 校验老人是否入住
     * @param idCardNo 老人身份证号
     * @param status 老人状态
     */
    private Elder checkElderIsAlreadyCheckIn(String idCardNo, Integer status) {
        LambdaQueryWrapper<Elder> qw = new LambdaQueryWrapper<Elder>()
                .eq(Elder::getIdCardNo, idCardNo);
        Elder elder = elderMapper.selectOne(qw);
        if(ObjectUtil.isNotNull(elder) && elder.getSex().equals(1)){
            throw new BaseException("操作失败，老人已入住");
        }
        // 当elder为null，或elder状态不为1时返回对象
        return elder;
    }

    /**
     * 查询入住详情
     *
     * @param id 入住id
     * @return 入住详情VO
     */
    @Override
    public CheckInDetailVo getCheckInDetail(Long id) {
        CheckInDetailVo detailVo = new CheckInDetailVo();
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        // 查询入住老人
        Elder elderDb = elderMapper.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elderDb, CheckInElderVo.class);
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elderDb.getIdCardNo()));
        detailVo.setCheckInElderVo(checkInElderVo);
        // 查询老人家属信息
        JSONArray jsonArray = JSONUtil.parseArray(checkIn.getRemark());
        List<ElderFamilyVo> familyVos = JSONUtil.toList(jsonArray, ElderFamilyVo.class);
        detailVo.setElderFamilyVoList(familyVos);
        // 查询入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(
                Wrappers.<CheckInConfig>lambdaQuery()
                        .eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        detailVo.setCheckInConfigVo(checkInConfigVo);
        // 查询入住合同信息
        Contract contract = contractMapper.selectOne(
                Wrappers.<Contract>lambdaQuery()
                        .eq(Contract::getElderId, checkInElderVo.getId())
        );
        detailVo.setContract(contract);
        return detailVo;
    }
}
